import React, { Component } from 'react';
import { DeleteOutlined } from '@ant-design/icons';
import { Table, Input } from 'antd';
import styles from './KeyValueTable.module.less';
import { IParam } from './../../configs/baseConfig';

export class KeyValueTable extends Component {

  state = {
    selectedRowKeys: [],
    dataSource: []
  }

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.initData();
  }

  componentDidUpdate(prevProps, preState) {
    if (prevProps.nodeKey !== this.props.nodeKey) {
      this.initData();
    }
  }

  initData = () => {
    const selectedRowKeys = [];
    const dataSource = this.props.dataSource && [...this.props.dataSource, new IParam()] || [new IParam()];
    dataSource.forEach(item => {
      if (item.isChecked && !selectedRowKeys.includes(item.key)) {
        selectedRowKeys.push(item.key);
      }
    });
    this.updateKeyValue({ dataSource, selectedRowKeys });
  }

  updateKeyValue = (stateData, callback) => {
    const dataSource = stateData && stateData.dataSource;
    if (!Array.isArray(dataSource)) {
      return;
    }

    this.setState(stateData, () => {
      if (typeof callback === 'function') {
        callback();
      }
      const dataSourceResult = [];
      for (let i = 0, length = dataSource.length; i < length; i++) {
        const { inputNameRef, inputValueRef, ...callbackData } = dataSource[i];
        if (!callbackData.name && !callbackData.value) {
          continue;
        }
        dataSourceResult.push(callbackData);
      }
      if (typeof this.props.updateKeyValue === 'function') {
        this.props.updateKeyValue(dataSourceResult);
      }
    });

  }

  itemInputChange = (value, item, fieldName) => {
    item[fieldName] = value;
    const dataSource = [...this.state.dataSource];
    const selectedRowKeys = [...this.state.selectedRowKeys];
    if (dataSource.every(item => item.name)) {
      const param = new IParam();
      dataSource.push(param);
      selectedRowKeys.push(param.key);
    }
    this.updateKeyValue({
      dataSource,
      selectedRowKeys
    }, () => {
      if (fieldName === 'name') {
        item.inputNameRef.focus();
      } else if (fieldName === 'value') {
        item.inputValueRef.focus();
      }
    });
  }

  deleteItem = (e) => {
    if (!e || !e.key) {
      return;
    }
    const dataSource = [...this.state.dataSource].filter(item => item.key !== e.key);
    const selectedRowKeys = [...this.state.selectedRowKeys].filter(item => item !== e.key);
    if (dataSource.length === 1 && dataSource[0].name) {
      const param = new IParam();
      dataSource.push(param);
      selectedRowKeys.push(param.key);
    }
    this.updateKeyValue({ dataSource, selectedRowKeys });
  }

  render() {
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        render: (field, item) => {
          return <>
            <Input
              value={field}
              ref={ref => item.inputNameRef = ref}
              onChange={e => this.itemInputChange(e.target.value, item, 'name')}
            />
          </>
        }
      },
      {
        title: 'Value',
        dataIndex: 'value',
        render: (field, item) => {
          return <>
            <Input
              value={field}
              ref={ref => item.inputValueRef = ref}
              onChange={e => this.itemInputChange(e.target.value, item, 'value')}
            />
          </>
        }
      },
      {
        title: 'Action',
        dataIndex: 'action',
        render: (_, item) => {
          return <>
            {
              this.state.dataSource.length > 1 ? <div className={styles.deleteContent} onClick={() => this.deleteItem(item)}>
                <DeleteOutlined />
              </div> : '-'
            }
          </>
        }
      }
    ];


    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selected, item, index) => {
        const dataSource = [...this.state.dataSource].map(item => ({
          ...item, isChecked: selected.includes(item.key)
        }));

        this.updateKeyValue({
          selectedRowKeys: selected,
          dataSource
        })
      },
    };

    return (
      <>
        <div className={styles.keyValueTable}>
          <Table rowSelection={rowSelection} columns={columns} dataSource={this.state.dataSource} pagination={false}
            rowClassName={() => styles.tableRowItem} />
        </div>
      </>
    );
  }
}